/*
 * @Description  :
 * @Author       : YiDing Xue
 * @Date         : 2023-01-12
 * @LastEditors  : YiDing Xue
 * @LastEditTime : 2023-03-10
 */
import { getToken } from '@/utils'
import { resolveResError } from './helpers'
import { _token } from '@/utils/auth/token'

export function reqResolve(config) {
  // 处理不需要token的请求
  if (config.noNeedToken) {
    return config
  }

  const token =
    getToken() ||
    'eyJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiI5NzEiLCJpcCI6IjExMy4xMTYuMjIyLjI0NyIsImV4cCI6MTcwMTE3NDUwNn0.udxBcXvtVD11RBzJtcsqV-Y3CzmcmKcuAEANlTR7IJY'
  console.log('%c [ token ]-18', 'font-size:13px; background:#fd2063; color:#ff64a7;', token)
  // if (!token) {
  //   return Promise.reject({ code: 401, message: '登录已过期，请重新登录！' })
  // }

  /** 请求头加上 token */
  // const _token =
  //   'eyJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiI5NzEiLCJpcCI6IjE4My4xNy41OC4xMiIsImV4cCI6MTcwMDY0NTgyOX0.xXCmasIuGFdmrYw1CZmfk6jhQHt4VfzIYXKu1myPi8I'
  // config.headers.token = token
  config.headers.Authorization = token || _token
  return config
}

export function reqReject(error) {
  return Promise.reject(error)
}

export function resResolve(response) {
  // TODO: 处理不同的 response.headers
  const { data, config } = response
  if (data?.code !== 200) {
    const code = data?.code

    /** 根据code处理对应的操作，并返回处理后的message */
    const message = resolveResError(code, data?.message)

    /** 需要错误提醒 */
    window.$message?.warning(message)
    // !config.noNeedTip && window.$message?.error(message)
    return Promise.reject({ code, message, error: data || response })
  }
  return Promise.resolve(data)
}

export function resReject(error) {
  if (!error || !error.response) {
    const code = error?.code
    /** 根据code处理对应的操作，并返回处理后的message */
    const message = resolveResError(code, error.message)
    window.$message?.error(message)
    return Promise.reject({ code, message, error })
  }
  const { data, status, config } = error.response
  const code = data?.code ?? status
  const message = resolveResError(code, data?.msg ?? error.message)
  /** 需要错误提醒 */
  !config?.noNeedTip && window.$message?.error(message)
  return Promise.reject({ code, message, error: error.response?.data || error.response })
}
